#include "room_manager.hpp"
#include <sstream>
#include <iostream>

RoomManager room_manager;

void RoomManager::join_room(int fd, const std::string& room_name, const std::string& pwd) {
    std::lock_guard<std::mutex> lock(mtx);

    std::string old_room = user_rooms[fd];
    user_rooms[fd] = room_name;

    rooms[room_name].insert(fd);
    if (!old_room.empty() && old_room != room_name) {
        rooms[old_room].erase(fd);
    }

    std::cout << "[RoomManager] fd=" << fd << " joined room '" << room_name << "'\n";
}

void RoomManager::leave_room(int fd) {
    std::lock_guard<std::mutex> lock(mtx);

    std::string room = user_rooms[fd];
    if (!room.empty()) {
        rooms[room].erase(fd);
        user_rooms[fd] = "";
        std::cout << "[RoomManager] fd=" << fd << " left room '" << room << "'\n";
    }
}

std::string RoomManager::get_room(int fd) {
    std::lock_guard<std::mutex> lock(mtx);
    return user_rooms.count(fd) ? user_rooms[fd] : "lobby";
}

std::string RoomManager::list_members(const std::string& room_name) {
    std::lock_guard<std::mutex> lock(mtx);
    std::ostringstream oss;
    for (int fd : rooms[room_name]) {
        oss << fd << " ";
    }
    return oss.str();
}

